package com.ams.thread.lesson7;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author： 乐哥聊编程(全平台同号)
 */
public class ReentrantMutexLock implements Lock {
    private final LockAQS lockAQS = new LockAQS();

    @Override
    public void lock() {
        lockAQS.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        lockAQS.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return lockAQS.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return lockAQS.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        lockAQS.release(1);
    }

    @Override
    public Condition newCondition() {
        return lockAQS.newCondition();
    }

    private static class LockAQS extends AbstractQueuedSynchronizer {
        /**
         * 重新获取锁的逻辑，只有当前同步状态为0，才允许获取成功
         *
         * @param arg
         * @return
         */
        @Override
        protected boolean tryAcquire(int arg) {
            // 通过cas机制去设置新值，如果当前锁没有被占用，则期望值肯定为0 并且新值为 获取的资源数量
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
                // 当前则为重新获取同一把锁，则进行计数加1
            } else if (getExclusiveOwnerThread() == Thread.currentThread()) {
                return compareAndSetState(getState(), getState() + 1);
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            // 首先判断当前state 如果当前状态值不是大于0 则释放非法
            if (getState() == 0) {
                return false;
            }
            //  判断当前获取锁的线程是否是当前线程 如果是的，则可以释放锁，否则抛出异常
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            // 计数减去当前获取的资源
            setState(getState() - 1);
            // 计数为0，则代表全部释放，将独占线程标识置空
            if (getState() == 0) {
                setExclusiveOwnerThread(null);
            }
            return true;
        }

        Condition newCondition() {
            return new ConditionObject();
        }
    }

}
